package jp.wasabeef.glide.transformations;

import jp.wasabeef.glide.transformations.utility.Utils;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Texture;
import ohos.agp.utils.Color;
import ohos.media.image.PixelMap;

import java.security.MessageDigest;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.TransformationUtils;
import org.jetbrains.annotations.NonNls;

/**
 * CropCircleWithBorderTransformation
 */
public class CropCircleWithBorderTransformation extends BitmapTransformation {
    private static final int VERSION = 1;
    private static final String ID = "jp.wasabeef.glide.transformations.CropCircleWithBorderTransformation." + VERSION;

    private final int borderSize;
    private final int borderColor;

    /**
     * CropCircleWithBorderTransformation Constructor
     */
    public CropCircleWithBorderTransformation() {
        this.borderSize = Utils.toDp(4);
        this.borderColor = Color.BLACK.getValue();
    }

    /**
     * CropCircleWithBorderTransformation Constructor
     */
    public CropCircleWithBorderTransformation(int borderSize, int borderColor) {
        this.borderSize = borderSize;
        this.borderColor = borderColor;
    }

    @Override
    protected PixelMap transform(@NonNls BitmapPool Pool, @NonNls PixelMap pixelMap, int outWidth, int outHeight) {
        PixelMap bitmap = TransformationUtils.circleCrop(Pool, pixelMap, outWidth, outHeight);
        setCanvasBitmapDensity(pixelMap, bitmap);

        Paint paint = new Paint();
        paint.setColor(new Color(borderColor));
        paint.setStyle(Paint.Style.STROKE_STYLE);
        paint.setStrokeWidth(borderSize);
        paint.setAntiAlias(true);

        Canvas canvas = new Canvas(new Texture(bitmap));
        canvas.drawCircle(
                outWidth / 2f,
                outHeight / 2f,
                Math.max(outWidth, outHeight) / 2f - borderSize / 2f,
                paint
        );

        return bitmap;
    }


    @Override
    public void updateDiskCacheKey(@NonNls MessageDigest messageDigest) {
        messageDigest.update((ID + borderSize + borderColor).getBytes(CHARSET));
    }

    @Override
    public boolean equals(Object object) {
        if (object instanceof CropCircleWithBorderTransformation) {
            CropCircleWithBorderTransformation crop = (CropCircleWithBorderTransformation) object;
            return crop.borderSize == borderSize && crop.borderColor == borderColor;

        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return ID.hashCode() + borderSize * 100 + borderColor + 10;
    }
}
